import asyncpg
from starlette.applications import Starlette
from starlette.requests import Request
from starlette.responses import Response, JSONResponse
from starlette.routing import Route


async def create_database_pool():
    print("创建数据库池...")
    pool = await asyncpg.create_pool(
        host="127.0.0.1",
        port=5432,
        user="around",
        password="zhouwei",
        database="products",
        min_size=6,
        max_size=6,
    )
    app.state.DB = pool


async def destroy_database_pool(app):
    print("销毁数据库连接池...")
    pool = app.state.DB
    await pool.close()


async def brand(request: Request):
    connection = request.app.state.DB
    brand_query = "select brand_id, brand_name from brand"
    results = await connection.fetch(brand_query)
    result_as_dict = [dict(brand) for brand in results]
    return JSONResponse(result_as_dict)


app = Starlette(
    routes=[
        Route("/brand", endpoint=brand),
    ],
    on_startup=[
        create_database_pool
    ],
    on_shutdown=[
        destroy_database_pool
    ],
)
